from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
import os


def docx_to_markdown(docx_path, output_dir="output"):
    """
    将Word转换为Markdown并保留对齐、下划线等样式
    Markdown不支持的特性用HTML标签实现
    """
    os.makedirs(output_dir, exist_ok=True)

    doc = Document(docx_path)
    filename = os.path.splitext(os.path.basename(docx_path))[0]
    md_path = os.path.join(output_dir, f"{filename}.md")
    txt_path = os.path.join(output_dir, "markdown.txt")  # 新增的txt文件路径

    markdown_lines = []

    for para in doc.paragraphs:
        text = para.text.strip()
        if not text:
            continue

        # 处理对齐样式
        alignment = para.paragraph_format.alignment
        is_centered = alignment == WD_ALIGN_PARAGRAPH.CENTER
        is_right_aligned = alignment == WD_ALIGN_PARAGRAPH.RIGHT

        # 处理文本样式（加粗、斜体、下划线）
        formatted_text = []
        for run in para.runs:
            run_text = run.text
            if run.bold:
                run_text = f"**{run_text}**"
            if run.italic:
                run_text = f"*{run_text}*"
            if run.underline:
                run_text = f"<u>{run_text}</u>"
            formatted_text.append(run_text)
        full_text = "".join(formatted_text)

        # 判断标题（根据字体大小和样式）
        heading_level = 0
        if para.runs and para.runs[0].font.size:
            size = para.runs[0].font.size.pt
            if size >= 24:
                heading_level = 1
            elif size >= 20:
                heading_level = 2
            elif size >= 16:
                heading_level = 3
            elif size >= 14:
                heading_level = 4

        # 构建Markdown行
        if heading_level > 0:
            line = f"{'#' * heading_level} {full_text}"
        elif para.style.name.startswith('List'):
            line = f"- {full_text}"
        else:
            line = full_text

        # 添加对齐样式
        if is_centered:
            line = f"<div align='center'>{line}</div>"
        elif is_right_aligned:
            line = f"<div align='right'>{line}</div>"

        markdown_lines.append(f"{line}\n\n")

    # 处理表格（保留基本对齐）
    for table in doc.tables:
        markdown_lines.append("\n")

        # 获取列对齐方式
        aligns = []
        for cell in table.rows[0].cells:
            if cell.paragraphs[0].paragraph_format.alignment == WD_ALIGN_PARAGRAPH.CENTER:
                aligns.append(":---:")
            elif cell.paragraphs[0].paragraph_format.alignment == WD_ALIGN_PARAGRAPH.RIGHT:
                aligns.append("---:")
            else:
                aligns.append("---")

        # 表头
        headers = [cell.text.strip() for cell in table.rows[0].cells]
        markdown_lines.append(f"| {' | '.join(headers)} |\n")
        # 分隔线
        markdown_lines.append(f"| {' | '.join(aligns)} |\n")
        # 表格内容
        for row in table.rows[1:]:
            cells = [cell.text.strip() for cell in row.cells]
            markdown_lines.append(f"| {' | '.join(cells)} |\n")
        markdown_lines.append("\n")

    # 将所有Markdown内容合并为一个字符串
    markdown_content = "".join(markdown_lines)

    # 写入.md文件
    with open(md_path, 'w', encoding='utf-8') as f:
        f.write(markdown_content)

    # 新增：同时写入markdown.txt文件
    with open(txt_path, 'w', encoding='utf-8') as f:
        f.write(markdown_content)

    print(f"转换完成！Markdown文件已保存到: {md_path}")
    print(f"Markdown内容也已保存到: {txt_path}")
    return md_path, txt_path  # 返回两个文件路径


# 使用示例
if __name__ == "__main__":
    docx_file = "resources/治安调解协议书.docx"  # 替换为你的文件路径
    md_file, txt_file = docx_to_markdown(docx_file)  # 获取两个文件路径